<?php

namespace app\admin\controller;

use think\Controller;

/**
 * Class Base
 * @package app\admin\controller
 * 后台基础类库
 */
class Base extends Controller
{
    /**
     * page
     * @var string
     */
    public $page = '';
    /**
     *每页显示多少条
     * @var string
     */
    public $size = '';

    /**
     * 查询条件的起始值
     * @var int
     */
    public $from = 0;

    /**
     * 定义model
     * @var string
     */
    public $model = '';

    //初始化
    public function _initialize()
    {
        //判断用户是否登录
        $isLogin = $this->isLogin();
        if (!$isLogin) {
            return $this->redirect('Login/index');
        }
    }

    /**
     * @return bool
     * 判断是否登录
     */
    public function isLogin()
    {
        //获取session
        $user = session(config('admin.session_user'), '', config('admin.session_user_scope'));
        if ($user && $user->id) {
            return true;
        }
        return false;
    }

    /**
     * 获取分页page size 内容
     */
    public function getPageAndSize($data)
    {
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : config('paginate.list_rows');
        $this->from = ($this->page - 1) * $this->size;
    }

    /**
     *删除
     */
    public function delete($id = 0)
    {
        if (!intval($id)) {
            return $this->result('', 0, 'ID不合法');
        }
        //如果表和控制器名字一样。
        //但是 如果表和控制器不一样
        $model = request()->controller();
        try {
            $res = $this->model ? $this->model : model($model)->save(['status' => -1], ['id' => $id]);

        } catch (\Exception $e) {
            return $this->result('', 0, $e->getMessage());
        }
        if ($res) {
            return $this->result(['jump_url' => $_SERVER['HTTP_REFERER']], 1, 'ok');
        }
        return $this->result('', 0, '删除失败！');
    }

    /**
     * 通用化修改状态
     */
    public function status()
    {
        $data = input('param.');
        //validate 机制校验 未完成

        //通过id去库中查询记录是否存在
        //model('News')->get($data['id']);
        $model = request()->controller();
        try {
            $res = $this->model ? $this->model : model($model)->save(['status' => $data['status']], ['id' => $data['id']]);

        } catch (\Exception $e) {
            return $this->result('', 0, $e->getMessage());
        }
        if ($res) {
            return $this->result(['jump_url' => $_SERVER['HTTP_REFERER']], 1, 'ok');
        }
        return $this->result('', 0, '修改失败！');
    }


}
